package io.renren.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.demo.spring.service.WeixinService;

import org.springframework.stereotype.Controller;

import io.renren.entity.WeixinMenu;
import io.renren.service.WeixinMenuService;

import io.renren.utils.PageUtils;
import io.renren.utils.R;
import me.chanjar.weixin.common.exception.WxErrorException;


/**
 * 微信菜单
 * 
 * @author zk
 * @email zk13899@163.com
 * @date 2017-07-21 15:22:07
 */
@Controller
@RequestMapping("weixinmenu")
public class WeixinMenuController {
	@Autowired
	private WeixinMenuService weixinMenuService;
	 @Autowired
	  private WeixinService wxService;
	@RequestMapping("/weixinmenu.html")
	public String list(){
		return "weixinmenu/weixinmenu.html";
	}
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("weixinmenu:list")
	public R list(Integer page, Integer limit){
		
				Map<String, Object> map = new HashMap<>();
				map.put("parentId", "0");
				List<WeixinMenu> listParent=weixinMenuService.queryListByParent(map);
				
				Map<String, Object> map1 = new HashMap<>();
				List<WeixinMenu> list=weixinMenuService.queryListByParent(map1);
				
				List<WeixinMenu> newList=new ArrayList<>();
				for(WeixinMenu m:listParent){
					m.setParentid("无上级菜单");
					newList.add(m);
					for(WeixinMenu l:list){
						if(l.getParentid().equals(m.getId().toString())){
							
							l.setName("|--->"+l.getName());
							
							l.setParentid(l.getParentName());
							
							newList.add(l);
						}
					}
				}
				int offset=(page - 1) * limit;
				
			
				List<WeixinMenu> listStream=newList.stream().skip(offset)
		                .collect(Collectors.toList());
				List<WeixinMenu> weixinMenuList=listStream.stream().limit(limit)
		                .collect(Collectors.toList());
		
		int total = weixinMenuService.queryTotal(map);
		
		PageUtils pageUtil = new PageUtils(weixinMenuList, total, limit, page);
		
		return R.ok().put("page", pageUtil);
	}
	
		/**
	 * 信息
	 */
	@ResponseBody
	@RequestMapping("/info/{id}")
	@RequiresPermissions("weixinmenu:info")
	public R info(@PathVariable("id") Integer id){
		WeixinMenu weixinMenu = weixinMenuService.queryObject(id);
	
		
		return R.ok().put("weixinMenu", weixinMenu);
	}
	
	@ResponseBody
	@RequestMapping("/info/parent")
	
	public R info(){

		Map<String, Object> map = new HashMap<>();
		map.put("parentid", "0");

//查询列表数据
		List<WeixinMenu> parent = weixinMenuService.queryList(map);
		
		return R.ok().put("parent", parent);
	}
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("/save")
	@RequiresPermissions("weixinmenu:save")
	public R save(@RequestBody WeixinMenu weixinMenu){
		weixinMenu.setCreatetime(new Date());
		weixinMenuService.save(weixinMenu);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("weixinmenu:update")
	public R update(@RequestBody WeixinMenu weixinMenu){
		weixinMenuService.update(weixinMenu);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("weixinmenu:delete")
	public R delete(@RequestBody Integer[] ids){
		weixinMenuService.deleteBatch(ids);
		
		return R.ok();
	}
	/**
	 * 微信端生成菜单
	 */
	@ResponseBody
	@RequestMapping("/menuCreate")
	@RequiresPermissions("weixinmenu:createMenu")
	public R createMenu(@RequestBody Integer[] ids){
		weixinMenuService.updateAllStatus();
		weixinMenuService.updateSomeStatus(ids);
		List<WeixinMenu> list=weixinMenuService.queryListByIds(ids);
		String json=createMenuJson(list);
		try {
			wxService.getMenuService().menuCreate(json);
		} catch (WxErrorException e) {
			
			e.printStackTrace();
			return R.error("微信端菜单生成失败");
		}
		return R.ok();
	}
	/**
	 * 微信端清空菜单
	 */
	@ResponseBody
	@RequestMapping("/menuDelete")
	@RequiresPermissions("weixinmenu:deleteMenu")
	public R deleteMenu(){
		
		try {
			wxService.getMenuService().menuDelete();
		} catch (WxErrorException e) {
			
			e.printStackTrace();
			return R.error("微信端清空菜单失败");
		}
		return R.ok("操作成功");
	}
	  private static String createMenuJson(List<WeixinMenu> list) {
	    	String json = "{\"button\":[";
			String str = "";
			for (WeixinMenu menu : list) {
				if("0".equals(menu.getParentid())){
					String subMenu = "";
					for (WeixinMenu menu1 : list) {
						if(menu1.getParentid().equals(String.valueOf(menu.getId()))){
							if("click".equals(menu1.getType())){
								subMenu += ",{\"type\":\"click\",\"name\":\""+menu1.getName()+"\",\"key\":\""+menu1.getKey()+"\"}";
							}
							else if("view".equals(menu1.getType())){
								String url = menu1.getUrl();
								subMenu += ",{\"type\":\"view\",\"name\":\""+menu1.getName()+"\",\"url\":\""+url+"\"}";
							}
						}
					}
					if(null == subMenu || "".equals(subMenu)){
						if("click".equals(menu.getType())){
							str += ",{\"type\":\"click\",\"name\":\""+menu.getName()+"\",\"key\":\""+menu.getKey()+"\"}";
						} else if("view".equals(menu.getType())){
							String url = menu.getUrl();
							str += ",{\"type\":\"view\",\"name\":\""+menu.getName()+"\",\"url\":\""+url+"\"}";
						}
					}else{
						str +=  ",{\"name\":\""+menu.getName()+"\",\"sub_button\":[";
						str += subMenu.substring(1);
						str += "]}";
					}
				}
			}
			str = str.substring(1);
			str += "]}";
			json += str;
	
			
			return json;
	    }
	
}
